package com.dubbo.protocol.socket;

import com.dubbo.protocol.Client;
import com.dubbo.protocol.bean.Invocation;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;

public class SocketClient implements Client
{

    @Override
    public Object send(URL url, Invocation invocation)
    {
        try
        {
            Socket socket = new Socket(url.getHost(), url.getPort());
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(invocation);
            oos.flush();

            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Object obj = ois.readObject();
            System.out.println("client get return: " + obj);
            ois.close();
            return obj;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object send(Invocation invocation)
    {

        URL url = null;
        try
        {
            url = new URL("http","localhost", 8080, "/");
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        return this.send(url, invocation);
    }

    public static void main(String[] args)
    {
        Invocation ivc = new Invocation();
        ivc.setInterfaceName("com.dubbo.service.UserService");
        ivc.setMethodName("findList");
        ivc.setParamsClass(new Class[]{});
        ivc.setParamsValue(new Object[]{});

        new SocketClient().send(ivc);
    }
}
